package com.jk.vehicle.core.context;

import com.jk.vehicle.core.constants.ContextConstants;

import java.util.HashMap;
import java.util.Map;


/**
 * 全局基础上下文
 *
 * @author KangJian
 * @date 2018/8/15
 */
public class BaseContextHolder {

	/**
	 * 本地线程变量
	 */
	private static ThreadLocal<Map<String, Object>> threadLocal = new ThreadLocal<Map<String, Object>>();

	/**
	 * set
	 * @param key
	 * @param value
	 */
	public static void set(String key, Object value) {
		Map<String, Object> map = threadLocal.get();
		if (map == null) {
			map = new HashMap<>();
			threadLocal.set(map);
		}
		map.put(key, value);
	}

	/**
	 * get
	 * @param key
	 * @return
	 */
	public static Object get(String key) {
		Map<String, Object> map = threadLocal.get();
		if (map == null) {
			map = new HashMap<>();
			threadLocal.set(map);
		}
		return map.get(key);
	}

	/**
	 * 获取用户ID
	 * @return
	 */
	public static String getUserID() {
		Object value = get(ContextConstants.CONTEXT_KEY_USER_ID);
		return returnObjectValue(value);
	}

	/**
	 * 获取用户openId
	 * @return
	 */
	public static String getOpenID() {
		Object value = get(ContextConstants.CONTEXT_KEY_OPEN_Id);
		return returnObjectValue(value);
	}

	/**
	 * 获取用户名称
	 * @return
	 */
	public static String getUsername() {
		Object value = get(ContextConstants.CONTEXT_KEY_USERNAME);
		return returnObjectValue(value);
	}

	/**
	 * 获取钉钉用户ID
	 * @return
	 */
	public static String getOriginatorUserId() {
		Object value = get(ContextConstants.ORIGINATOR_USER_ID);
		return returnObjectValue(value);
	}
	/**
	 * 获取钉钉用户部门Id
	 * @return
	 */
	public static String getDeptId() {
		Object value = get(ContextConstants.DEPT_ID);
		return returnObjectValue(value);
	}
	/**
	 * 设置用户ID
	 * @param userID
	 */
	public static void setUserID(String userID) {
		set(ContextConstants.CONTEXT_KEY_USER_ID, userID);
	}

	/**
	 * 设置微信openId
	 * @param openId
	 */
	public static void setOpenId(String openId) {
		set(ContextConstants.CONTEXT_KEY_OPEN_Id, openId);
	}

	/**
	 * 设置用户名称
	 * @param username
	 */
	public static void setUsername(String username) {
		set(ContextConstants.CONTEXT_KEY_USERNAME, username);
	}

	/**
	 * 设置钉钉用户
	 * @param originatorUserId
	 */
	public static void setOriginatorUserId(String originatorUserId) {
		set(ContextConstants.ORIGINATOR_USER_ID, originatorUserId);
	}

	/**
	 * 设置钉钉用户
	 * @param deptId
	 */
	public static void setDeptId(String deptId) {
		set(ContextConstants.DEPT_ID, deptId);
	}
	/**
	 * 获取对象值
	 * @param value
	 * @return
	 */
	private static String returnObjectValue(Object value) {
		return value == null ? null : value.toString();
	}

	/**
	 * 清除本地线程变量
	 */
	public static void remove() {
		threadLocal.remove();
	}
}
